package com.zly.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zly.dao.DormDao;
import com.zly.util.HibernateUtil;

public class DormDaoImpl<T> implements DormDao<T> {

	/**
	 * 实现接口查询数据的方法
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<T> select(Class<T> clazz, String sql) {
		Session session = HibernateUtil.openSession();
		Transaction tx = session.beginTransaction();
		List<T> list = null;
		try {
			list = session.createSQLQuery(sql).addEntity(clazz).list();// 查询数据
			tx.commit();
		} catch (Exception e) {
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			HibernateUtil.close(session);
		}
		return (List<T>) list;
	}
	/**
	 * 实现接口更新数据的方法
	 */
	@Override
	public void update(Object obj) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.openSession();
			tx = session.beginTransaction();
			session.update(obj);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			tx.commit();
			session.close();
		}
	}
	/**
	 * 实现接口增加数据的方法
	 * @param clazz
	 */
	@Override
	public void save(Object obj) {
		Session session=null;
		Transaction tx=null;
		try{
			//创建Session对象
		   session= HibernateUtil.openSession();
		   //开启事物
		   tx=session.beginTransaction();
		   //保存数据
		   session.save(obj);
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			//提交事物
			tx.commit();
			//关闭session
			session.close();
		}
		
	}

	/**
	 * 实现接口增加数据的方法
	 */
	/*public void save(Class<T> clazz) {
		// 开启事务
		Session session = HibernateUtil.openSession();
		session.beginTransaction();
		session.save(clazz);
		// 结束事务
		session.getTransaction().commit();
		session.close();
	}*/
	/**
	 * 删除用户
	 * @param clazz
	 */
	@Override
	public void delete(Object obj) {
		Session session=null;
		Transaction tx=null;
		try{
			session= HibernateUtil.openSession();
			tx=session.beginTransaction();
			session.delete(obj);
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			tx.commit();
			session.close();
		}	
	}
	/**
	 * 根据id删除用户
	 * @param clazz
	 * @param id
	 */
	@Override
	public void deleteById(Class<T> clazz,Serializable id) {
		Session session=null;
		Transaction tx=null;
		try{
			session= HibernateUtil.openSession();
			tx=session.beginTransaction();
			Object obj=session.get(clazz, id);
			if(obj!=null){
			   session.delete(obj);
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			tx.commit();
			session.close();
		}	
	}
}
